//
//  OpenSDK_LoginManager.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/19.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_LoginManager.h"
#import "OpenSDK.h"
#import "OpenSDK_EventManager.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_StatisticsManager.h"

#import "OpenSDK_Enum.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_EventKeys.h"
#import "OpenSDK_HttpUtil.h"
#import "OpenSDK_UserResData.h"
#import "OpenSDK_UserInfo.h"
#import "OpenSDK_VerificationCodeResData.h"
#import "OpenSDK_LoginProtocol.h"
#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"

@implementation OpenSDK_LoginManager

{
    UIViewController *registerViewRecord;
    OpenSDK_UserResData *curUserInfo;
}

static OpenSDK_LoginManager *instance = nil;

+(instancetype) getInstance {
    if(instance==nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
        });
    }
    return instance;
}

/**
 * 发出登录成功事件(由UI层调用，决定登录事件时机)
 */
-(void) sendLoginSuccessEvent {
    OpenSDK_AccountRecord *record = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (record == nil) {
        NSLog(@"当前没有登录，无法发出登录成功事件!");
        return;
    }
    
    NSString *loginType = @"";
    switch (record.accountType) {
        case OpenSDKAccountTypeDynamic:
            loginType = @"验证码登录";
            break;
        case OpenSDKAccountTypeMobile:
            loginType = @"手机号登录";   // 未使用
            break;
        case OpenSDKAccountTypeMail:
            loginType = @"账号登录";
            break;
        case OpenSDKAccountTypeGuest:
            loginType = @"快捷登录";
            break;
        case OpenSDKAccountTypeOther:
            if ([record.platform isEqual:@"WeChatLogin"]) {
                loginType = @"微信登录";
            } else if ([record.platform isEqual:@"QQ"]) {
                loginType = @"QQ登录";
            } else if ([record.platform isEqual:@"AppleLogin"]) {
                loginType = @"苹果登录";
            } else if ([record.platform isEqual:@"OneKey"]) {
                loginType = @"一键登录";
            } else {
                loginType = record.platformName ?: record.platform ?: @"";
            }
            break;
    }
    // 统计登陆成功
    [[OPKTracking shared] event:OPKEventLoginFinish parameters:@{OPKJReportKeyLoginType: loginType}];
    
    self.curOpenId = record.openId;
    self.curToken = record.token;
    OpenSDK_UserInfo *data = [[OpenSDK_UserInfo alloc] init];
    [data setOpenSDK_token:record.token];
    [data setOpenSDK_openID:record.openId];
    [data setOpenSDK_nickName:record.accountName];
    // 上报登录成功统计
    [[OpenSDK_StatisticsManager getInstance] sendLoginSuccessStatistics];
    // 发送内部登录成功事件
    [OpenSDK_EventManager postNotificationName:OPENSDK_EVENT_LOGIN_SUCCESS object:data];
    // 登录成功，回调外部
    if ([OpenSDK getInstance].delegate) {
        [[OpenSDK getInstance].delegate openSDKLoginWithCode:OpenSDK_LOGIN_SUCCESS userInfo:data errStr:nil];
    }
}

/**
 * 发出登录取消事件(由UI层调用，决定登录事件时机)
 */
-(void) sendLoginCacelEvent {
    //登录成功，回调外部
    if ([OpenSDK getInstance].delegate) {
        [[OpenSDK getInstance].delegate openSDKLoginWithCode:OpenSDK_LOGIN_CANCEL userInfo:nil errStr:nil];
    }
}

/**
 * 快捷登录
 */
-(void) loginWithRecord:(OpenSDK_AccountRecord *)record
               delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    if (record.accountType == OpenSDKAccountTypeGuest) {
        // 如果是游客，则调用游客登录接口
        [self loginWithGuest:record.accountValue delegate:delegate];
    } else {
        // 如果是其他账号类型，则调用快捷登录接口
        [OpenSDK_HttpUtil checkUserWithToken:record.token openID:record.openId httpDelegate:^(OpenSDK_BaseResData *resData) {
            if([resData isOk]) {
                //更新登录成功后的token和openId
                OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
                record.openId = [userInfo getOpenID];
                record.token = [userInfo getToken];
                record.mobile = [userInfo getMobile];
                record.userId = [userInfo getUser_id];
                record.isReal = [userInfo isReal];
                record.needReal = [userInfo needReal];
                //保存当前登录成功的账号
                [[OpenSDK_DataManager getInstance] setCurAccount:record];
                //添加历史记录
                [[OpenSDK_DataManager getInstance] addAccount:record];
                
                // 统计登录成功
                [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_LOGIN_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_AUTO];
                
                //回调登录成功
                if (delegate) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        delegate(YES, record, 0, nil);
                    });
                }
            } else {
                // 统计登录失败
                [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_LOGIN_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_AUTO failCode:[resData errorNo] failInfo:[resData errorMsg]];
                // 快捷登录失败
                if (delegate) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        delegate(NO, record, [resData errorNo], [resData errorMsg]);
                    });
                }
            }
        }];
    }
}

/**
 * 游客登录
 */
-(void) loginWithGuest:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    // 查询已有游客，用上次的游客账号登录
    NSString *tmpId = nil;
    NSArray *accounts = [[OpenSDK_DataManager getInstance] getAccountList:nil];
    for (OpenSDK_AccountRecord *account in accounts) {
        if (account.accountType == OpenSDKAccountTypeGuest) {
            tmpId = account.accountValue;
            break;
        }
    }
    [self loginWithGuest:tmpId delegate:delegate];
}

-(void) loginWithGuest:(NSString *)tmpId
              delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    [OpenSDK_HttpUtil loginWithTmpId:tmpId httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //更新登录成功后的tmpId
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            NSString *loginTmpId = [userInfo getNickName];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithGuest:loginTmpId openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] mobile:[userInfo getMobile] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //保存当前登录成功的账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计登录成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_LOGIN_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_TEMP];
            
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, 0, nil);
                });
            }
        } else {
            // 统计登录失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_LOGIN_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_TEMP failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 游客登录失败
            if (delegate) {
                delegate(NO, nil, [resData errorNo], [resData errorMsg]);
            }
        }
    }];
}

/**
 * 手机号登录
 */
-(void) loginWithPhone:(NSString *)phone
          securityCode:(NSString *)securityCode
              delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    //设置当前用户登录类型
    [OpenSDK_HttpUtil loginWithPhoneNumber:phone randomPasswd:securityCode  httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录登录成功后的token
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithMobile:phone type:OpenSDKAccountTypeDynamic openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //保存当前登录成功的账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计登录成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_LOGIN_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_PHONE];
            
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, 0, nil);
                });
            }
        } else {
            // 统计登录失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_LOGIN_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_PHONE failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 手机登录失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorNo], [resData errorMsg]);
                });
            }
        }
    }];
}

/**
 * 邮箱登录
 */
-(void) loginWithMail:(NSString *)mail
             password:(NSString *)password
             delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    [OpenSDK_HttpUtil loginWithUserName:mail passwd:password httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithMail:mail openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] mobile:[userInfo getMobile] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //设置当前账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计登录成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_LOGIN_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL];
            
            //回调登录成功
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, 0, nil);
                });
            }
        } else {
            // 统计登录失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_LOGIN_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 邮箱登录失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorNo], [resData errorMsg]);
                });
            }
        }
    }];
}

// 手机号密码登录
-(void) loginWithMobile:(NSString *)mobile
             password:(NSString *)password
             delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    [OpenSDK_HttpUtil loginWithPhoneNumber:mobile passwd:password httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithMobile:mobile type:OpenSDKAccountTypeMobile openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //设置当前账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计登录成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_LOGIN_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL];
            
            //回调登录成功
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, 0, nil);
                });
            }
        } else {
            // 统计登录失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_LOGIN_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 登录失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorNo], [resData errorMsg]);
                });
            }
        }
    }];
}

// 一键登录
-(void) loginWithOneKeyToken:(NSString *)token
             delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    [OpenSDK_HttpUtil loginWithOneKeyToken:token httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithMobile:[userInfo getMobile] type:OpenSDKAccountTypeOther openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //设置当前账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计登录成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_LOGIN_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL];
            
            //回调登录成功
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, 0, nil);
                });
            }
        } else {
            // 统计登录失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_LOGIN_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 登录失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorNo], [resData errorMsg]);
                });
            }
        }
    }];
}


/**
 * 第三方平台登录
 */
-(void) loginWithPlatform:(NSString *)serverName
                 delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err))delegate {
    id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:serverName];
    if (sdk == nil) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate(NO, nil, 0, @"不支持此登录方式");
            });
        }
        return;
    }
    NSString *platformName = [sdk getDisplayName];
    NSString *platform = [sdk getPlatform];
    sdk.loginDelegate = ^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithOtherSDK:[userInfo getNickName] platform:platform platformName:platformName platformUid:[userInfo getOpenID] openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] mobile:[userInfo getMobile] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            if ([userInfo isMobile]) {
                //设置当前账号
                [[OpenSDK_DataManager getInstance] setCurAccount:record];
                //添加历史记录
                [[OpenSDK_DataManager getInstance] addAccount:record];
            } else {
                //设置预登陆账号
                [[OpenSDK_DataManager getInstance] setPreLoginAccount:record];
            }
            
            
            //回调登录成功
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, 0, nil);
                });
            }
        } else {
            // 第三方登录失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorNo], [resData errorMsg]);
                });
            }
        }
    };
    // 调起sdk的登录接口
    dispatch_async(dispatch_get_main_queue(), ^{
        [sdk startLogin];
    });
}

-(void) authWithPlatform:(NSString *)serverName
                 delegate:(void (^)(BOOL result, NSDictionary *content, long errorNo, NSString *err))delegate {
    id<OpenSDK_LoginProtocol> sdk = [[OpenSDK_DataManager getInstance].supportSDKServerNames objectForKey:serverName];
    if (sdk == nil) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate(NO, nil, 0, @"不支持此登录方式");
            });
        }
        return;
    }
    sdk.loginDelegate = ^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //回调登录成功
            NSDictionary *content = [resData content];
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, content, 0, nil);
                });
            }
        } else {
            // 第三方登录失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorNo], [resData errorMsg]);
                });
            }
        }
    };
    // 调起sdk的登录接口
    dispatch_async(dispatch_get_main_queue(), ^{
        [sdk startAuth];
    });
}

/**
 * 注销登录(清除账号记录)
 */
-(void) logout {
    // TODO 如果当前账号是游客，则注销登录时，应该要提醒用户吧。注销完后，要删除账号记录
    if(self.curOpenId != nil && self.curToken != nil) {
        [OpenSDK_HttpUtil logoutWithToken:self.curToken UID:self.curOpenId httpDelegate:^(OpenSDK_BaseResData *resData) {
            if(![resData isOk]) {
                if ([OpenSDK getInstance].delegate) {
                    [[OpenSDK getInstance].delegate openSDKLoginWithCode:OpenSDK_LOGOUT_FAIL userInfo:nil errStr:[resData errorMsg]];
                }
                return;
            }
            // 清空历史记录
            [[OpenSDK_DataManager getInstance] removeAccountByOpenId:self.curOpenId];
            // 情况当前账号
            if ([OpenSDK_DataManager getInstance].currentAccount.openId == self.curOpenId) {
                NSArray *accounts = [[OpenSDK_DataManager getInstance] getAccountList:nil];
                if (accounts != nil && accounts.count > 0) {
                    [[OpenSDK_DataManager getInstance] setCurAccount:[accounts objectAtIndex:0]];
                } else {
                    [[OpenSDK_DataManager getInstance] setCurAccount:nil];
                }
            }
            // 清空登录的uid和token
            self.curOpenId = nil;
            self.curToken = nil;
            // 发出登出消息
            [OpenSDK_EventManager postNotificationName:OPENSDK_EVENT_LOGOUT object:nil];
            // 回调登出
            if ([OpenSDK getInstance].delegate) {
                [[OpenSDK getInstance].delegate openSDKLoginWithCode:OpenSDK_LOGOUT_SUCCESS userInfo:nil errStr:nil];
            }
        }];
    }
}

- (void)localLogout {
    if(self.curOpenId != nil && self.curToken != nil) {
        // 清空历史记录
        [[OpenSDK_DataManager getInstance] removeAccountByOpenId:self.curOpenId];
        // 情况当前账号
        if ([OpenSDK_DataManager getInstance].currentAccount.openId == self.curOpenId) {
            NSArray *accounts = [[OpenSDK_DataManager getInstance] getAccountList:nil];
            if (accounts != nil && accounts.count > 0) {
                [[OpenSDK_DataManager getInstance] setCurAccount:[accounts objectAtIndex:0]];
            } else {
                [[OpenSDK_DataManager getInstance] setCurAccount:nil];
            }
        }
        // 清空登录的uid和token
        self.curOpenId = nil;
        self.curToken = nil;
        // 发出登出消息
        [OpenSDK_EventManager postNotificationName:OPENSDK_EVENT_LOGOUT object:nil];
        // 回调登出
        if ([OpenSDK getInstance].delegate) {
            [[OpenSDK getInstance].delegate openSDKLoginWithCode:OpenSDK_LOGOUT_SUCCESS userInfo:nil errStr:nil];
        }
    }
}

- (void)localLogoutNotClean {
    if(self.curOpenId != nil && self.curToken != nil) {
        // 清空登录的uid和token
        self.curOpenId = nil;
        self.curToken = nil;
        // 发出登出消息
        [OpenSDK_EventManager postNotificationName:OPENSDK_EVENT_LOGOUT object:nil];
        // 回调登出
        if ([OpenSDK getInstance].delegate) {
            [[OpenSDK getInstance].delegate openSDKLoginWithCode:OpenSDK_LOGOUT_SUCCESS userInfo:nil errStr:nil];
        }
    }
}

/**
 * 发送短信
 */
-(void) sendSMS:(NSString *)phone
        smsType:(NSString *)smsType
       delegate:(void (^)(BOOL result, long validTime, NSString *err))delegate {
    [OpenSDK_HttpUtil sendSMSWithPhoneNumber:phone smsType:smsType httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            // 发送短信成功
            if (delegate) {
                OpenSDK_VerificationCodeResData *verificationData=[[OpenSDK_VerificationCodeResData alloc] initWithDictionary:[resData content]];
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, [verificationData getVerificationCodeValidTime], nil);
                });
            }
        } else {
            // 发送短信失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, 0, [resData errorMsg]);
                });
            }
        }
    }];
}

/**
 * 将当前账号绑定手机号
 */
-(void) bindWithPhone:(NSString *)phone
         securityCode:(NSString *)securityCode
             delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, NSString *err))delegate {
    OpenSDK_AccountRecord *preLoginAccount = [[OpenSDK_DataManager getInstance] getPreLoginAccount];
    if (preLoginAccount == nil) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate(NO, nil, @"抱歉，无法绑定手机号");
            });
        }
        return;
    }
    
    NSString *platform = preLoginAccount.platform;
    if (preLoginAccount.accountType == OpenSDKAccountTypeMail) {
        platform = @"Account";
    }
    platform = platform ?: @"";
    
    [OpenSDK_HttpUtil bindingWithPhoneNumber:phone passwd:nil randomPassword:securityCode openId:preLoginAccount.openId token:preLoginAccount.token platform:platform httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录登录成功后的token
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithMobile:phone type:OpenSDKAccountTypeDynamic openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //保存当前登录成功的账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计绑定手机号成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_TEMPORARY_BIND_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_TEMP];
            
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, nil);
                });
            }
        } else {
            // 统计绑定失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_TEMPORARY_BIND_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_TEMP failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 绑定手机失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorMsg]);
                });
            }
        }
    }];
}

/**
 * 邮箱注册
 */
-(void) registerWithMail:(NSString *)mail
                password:(NSString *)password
                delegate:(void (^)(BOOL result, OpenSDK_AccountRecord *account, NSString *err))delegate {
    [OpenSDK_HttpUtil registerWithUserName:mail passwd:password httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            //记录登录成功后的token
            OpenSDK_UserResData *userInfo = [[OpenSDK_UserResData alloc] initWithData:[resData content]];
            OpenSDK_AccountRecord *record = [OpenSDK_AccountRecord initWithMail:mail openId:[userInfo getOpenID] token:[userInfo getToken] userId:[userInfo getUser_id] mobile:[userInfo getMobile] isReal:[userInfo isReal] needReal:[userInfo needReal] isMobile:[userInfo isMobile] needMobile:[userInfo needMobile]];
            //保存当前登录成功的账号
            [[OpenSDK_DataManager getInstance] setCurAccount:record];
            //添加历史记录
            [[OpenSDK_DataManager getInstance] addAccount:record];
            
            // 统计邮箱注册成功
            [[OpenSDK_StatisticsManager getInstance] collectLoginSuccessWithType:OPENSDK_STATS_REGISTER_SUCCESS detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL];
            
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, record, nil);
                });
            }
        } else {
            // 统计注册失败
            [[OpenSDK_StatisticsManager getInstance] collectLoginFailWithType:OPENSDK_STATS_REGISTER_FAIL detail:OPENSDK_STATS_DETAIl_LOGIN_EMAIL failCode:[resData errorNo] failInfo:[resData errorMsg]];
            // 邮箱注册失败
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, nil, [resData errorMsg]);
                });
            }
        }
    }];
}

/**
 * 查询当前账号是否实名认证
 */
-(void) checkRealnameWithDelegate:(void (^)(BOOL result, BOOL isReal, NSString *err))delegate {
    OpenSDK_AccountRecord *curAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (curAccount == nil) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate(NO, NO, @"抱歉，没有登录账号，无法进行实名认证");
            });
        }
        return;
    }
    [OpenSDK_HttpUtil checkRealNameWithOpenID:curAccount.openId token:curAccount.token httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            BOOL isReal=[[[resData content] objectForKey:OpenSDK_S_IS_REAL] boolValue];
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, isReal, nil);
                });
            }
        } else {
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, NO, [resData errorMsg]);
                });
            }
        }
    }];
}

/**
 * 对当前账号进行实名认证
 */
-(void) realnameWithName:(NSString *)name
                    card:(NSString *)card
                   phone:(NSString *)phone
            securityCode:(NSString *)securityCode
                delegate:(void (^)(BOOL result, NSString *err))delegate {
    OpenSDK_AccountRecord *curAccount = [[OpenSDK_DataManager getInstance] getCurAccount];
    if (curAccount == nil) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate(NO, @"抱歉，没有登录账号，无法进行实名认证");
            });
        }
        return;
    }
    
    [OpenSDK_HttpUtil realNameWithOpenID:curAccount.openId
                                   token:curAccount.token
                                realName:name
                              cardNumber:card
                             phoneNumber:phone
                                security:securityCode
                            httpDelegate:^(OpenSDK_BaseResData *resData) {
        if([resData isOk]) {
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(YES, nil);
                });
            }
        } else {
            if (delegate) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    delegate(NO, [resData errorMsg]);
                });
            }
        }
    }];
}

/**
 * 通过邮箱重置密码
 */
-(void) resetPassworkWithMail:(NSString *)mail
                delegate:(void (^)(BOOL result, NSString *err))delegate {
    [OpenSDK_HttpUtil findPasswordWithEmail:mail httpDelegate:^(OpenSDK_BaseResData *resData) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate([resData isOk], [resData errorMsg]);
            });
        }
    }];
}

/**
 * 查询绑定激活码信息
 */
-(void) checkActivationCodeWithDelegate:(void (^)(BOOL isBind, NSString *err))delegate {
    [OpenSDK_HttpUtil queryAppActiveStatus:[OpenSDK_DataManager getInstance].activeAffectData httpDelegate:^(OpenSDK_BaseResData *resData) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate([resData isOk], [resData errorMsg]);
            });
        }
    }];
}


/**
 * 绑定激活码
 */
-(void) bindActivationCode:(NSString *)code
                  delegate:(void (^)(BOOL isBind, NSString *err))delegate {
    [OpenSDK_HttpUtil bindActiveCode:code httpDelegate:^(OpenSDK_BaseResData *resData) {
        if (delegate) {
            dispatch_async(dispatch_get_main_queue(), ^{
                delegate([resData isOk], [resData errorMsg]);
            });
        }
    }];
}

@end
